package com.qjc.demo.algorithm.两个栈实现一个队列;

import javax.sound.midi.Soundbank;
import java.util.Stack;

/**
 * 两个栈实现一个队列：栈1只做入栈，栈2只做出栈，栈1入栈栈2出栈就实现了队列先进先出。
 * 元素入栈1后，依次取出放到栈2，这就栈1的数据就倒过来了，
 * 此时又有入栈的还是进入栈1，直到栈2全部清空，才能再次将栈1的数据传输到栈2里
 *
 * @ClassName: Solution
 * @Author: qjc
 * @Date: 2023/9/13 10:36
 */
public class Solution {

    Stack<String> stack1 = new Stack<>();
    Stack<String> stack2 = new Stack<>();

    public void inQueue(String element) {
        stack1.push(element);
    }

    public String outQueue() {
        if (!stack2.isEmpty()) {
            String pop = stack2.pop();
            return pop;
        }
        // 栈1的数据出栈，然后入栈到栈2中
        while (!stack1.isEmpty()) {
            String pop = stack1.pop();
            stack2.push(pop);
        }
        // 栈2的数据出栈
        return stack2.pop();
    }

    public boolean isEmpty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    public static void main(String[] args) {
        String[] items = {"A", "B", "C", "D", "E", "F"};
        Solution solution = new Solution();
        for (String s : items) {
            solution.inQueue(s);
        }
        while (!solution.isEmpty()) {
            String s = solution.outQueue();
            System.out.println(s);
        }
    }

}
